package m.store.service;

import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.base.util.PowerUtil;
import m.common.model.util.*;
import m.common.service.Service;
import m.store.model.*;
import m.store.task.GuestSaleSupport;
import m.store.task.MonthRecordSupport;
import m.store.task.SaleInfoIncomeSupport;
import m.system.exception.MException;
import m.system.util.ArrayUtil;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;

import java.util.*;

public class IncomeAmountService extends Service {
    public String save(IncomeAmount model, List<IncomeAmountRecord> saleList) throws Exception {
        if(null==saleList||saleList.isEmpty()) throw new MException(this.getClass(),"请添加出库订单");
        ModelQueryCheck.init(model)
            .checkNotNull("guest.oid","请选择收款客户")
            .checkNotNull("incomeDate","收款日期不能为空")
            .checkNotNull("status","状态错误")
            .checkStrEq("status", OrderModel.Status_Register,"登记状态才能修改")
            .doCheck(false,true);
        PowerUtil.verifyAccountDate(model.getIncomeDate(),"收款日期");
        String msg="";
        if(ObjectUtil.isEmptyOid(model)){
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            msg="保存成功";
        }else{
            ModelUpdateUtil.updateModel(model,"guest.oid","incomeDate","remark");
            msg="修改成功";
        }
        ModelUpdateUtil.delete(IncomeAmountRecord.class, QueryCondition.eq("income.oid",model.getOid()));
        SaleInfoService saleService=getService(SaleInfoService.class);
        Map<String,Double> amountMap=new HashMap<>();
        Set<String> error=new HashSet<>();
        for(IncomeAmountRecord record : saleList){
            ModelQueryCheck.init(record)
                .checkNotNull("sale.oid","请选择出库订单")
                .checkNotNull("incomeAmount","请输入收款金额")
                .doCheck(false,true);
            String saleOid=record.getSale().getOid();
            saleService.updateInIncomeAmount(saleOid);
            SaleInfo sale=ModelQueryList.getModel(record.getSale());
            if(null!=amountMap.get(saleOid)) throw new MException(this.getClass(),sale.getOrderNo()+" 重复添加了");
            amountMap.merge(saleOid, record.getIncomeAmount(), Double::sum);//累加相同商品数量
            if(NumberUtil.round(sale.getOweAmount()-sale.getInIncomeAmount()-amountMap.get(saleOid),2)<0)
                error.add(sale.getOrderNo());
            record.setOid(GenerateID.generatePrimaryKey());
            record.setIncome(model);
        }
        if(!error.isEmpty()) //收款已超出
            throw new MException(this.getClass(),"收款已超出 - "+ ArrayUtil.connection(error.toArray(),","));
        ModelUpdateUtil.insertModels(saleList.toArray(new IncomeAmountRecord[0]));
        updateAmount(model.getOid());
        return msg;
    }
    private void updateAmount(String oid) throws MException {
        ModelUpdate.init(IncomeAmount.class)
            .set("incomeAmount",IncomeAmountRecord.class,"ifnull(sum(#{incomeAmount}),0)",QueryCondition.eq("income.oid",oid))
            .execute(oid);
    }

    /**
     * 提交
     */
    public void saveAndSubmit(IncomeAmount model, List<IncomeAmountRecord> saleList) throws Exception {
        save(model,saleList);
        model.setStatus(OrderModel.Status_Check);
        model.setSubmitDate(new Date());
        ModelUpdateUtil.updateModel(model,"status","submitDate");
    }

    /**
     * 删除
     */
    public void delete(String oid, UserInfo user) throws Exception {
        IncomeAmount model=ModelQueryList.getModel(IncomeAmount.class,oid,"*");
        ModelQueryCheck.init(model)
            .checkStrEq("status",OrderModel.Status_Register,"登记中才能删除")
            .checkStrEq("inputUser.oid",user.getOid(),"权限错误")
            .doCheck(false,true);
        ModelUpdateUtil.deleteModel(model);
        ModelUpdateUtil.delete(IncomeAmountRecord.class, QueryCondition.eq("sale.oid",model.getOid()));
    }

    /**
     * 审核通过
     */
    public void check(String oid,Date incomeDate,String remark, StoreInfo store,UserInfo user) throws Exception {
        IncomeAmount model=ModelQueryList.getModel(IncomeAmount.class,oid,"*");
        model.setIncomeDate(incomeDate);
        model.setRemark(remark);
        ModelQueryCheck.init(model)
            .checkNotNull("incomeDate","收款日期不能为空")
            .checkStrEq("status",OrderModel.Status_Check,"审核中才能通过")
            .checkStrEq("store.oid",store.getOid(),"权限错误")
            .doCheck(false,true);
        PowerUtil.verifyAccountDate(model.getIncomeDate(),"收款日期");
        model.setStatus(OrderModel.Status_Done);
        model.setCheckUser(user);
        model.setCheckDate(new Date());
        ModelUpdateUtil.updateModel(model,"status","checkUser.oid","checkDate","incomeDate","remark");
        //关联到款金额
        getService(GuestBackAmountService.class).linkAmount(model);
        //更新库存收款信息
        ModelQueryList.getModelList(IncomeAmountRecord.class,
            new String[]{"sale.oid"},null,
            QueryCondition.eq("income.oid",model.getOid())
        ).forEach(item-> SaleInfoIncomeSupport.add(item.getSale().getOid()));
        SaleInfoIncomeSupport.start();
        //更新客户收款金额
        GuestSaleSupport.add(model.getGuest().getOid());
        GuestSaleSupport.start();
        //更新月度统计
        MonthRecordSupport.add(model.getInputUser().getOid(),model.getIncomeDate(), MonthRecord.Type_Income);
        MonthRecordSupport.start();
    }

    /**
     * 退回
     */
    public void refund(String oid, StoreInfo store,UserInfo user) throws Exception {
        IncomeAmount model=ModelQueryList.getModel(IncomeAmount.class,oid,"*");
        ModelQueryCheck.init(model)
            .checkStrEq("status",OrderModel.Status_Check,"审核中才能退回")
            .checkStrEq("store.oid",store.getOid(),"权限错误")
            .doCheck(false,true);
        model.setStatus(OrderModel.Status_Register);
        model.setCheckUser(user);
        model.setCheckDate(new Date());
        ModelUpdateUtil.updateModel(model,"status","checkUser.oid","checkDate");
    }
}
